<template>
  <div class="location-manage-page">
    <!-- 顶部筛选区 -->
    <el-card class="mb-3">
      <el-form :inline="true" :model="filter" @submit.prevent>
        <el-form-item label="所属仓库">
          <el-select v-model="filter.warehouse" placeholder="全部仓库" clearable style="width: 160px;">
            <el-option v-for="w in warehouseList" :key="w.id" :label="w.name" :value="w.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="分区">
          <el-select v-model="filter.zone" placeholder="全部分区" clearable style="width: 140px;">
            <el-option v-for="z in zoneList" :key="z.id" :label="z.name" :value="z.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="货架">
          <el-select v-model="filter.shelf" placeholder="全部货架" clearable style="width: 120px;">
            <el-option v-for="s in shelfList" :key="s.id" :label="s.name" :value="s.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filter.status" placeholder="全部状态" clearable style="width: 120px;">
            <el-option label="可用" value="available" />
            <el-option label="占用" value="occupied" />
            <el-option label="锁定" value="locked" />
            <el-option label="禁用" value="disabled" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input v-model="filter.keyword" placeholder="库位编号/条码/备注" clearable style="width: 180px;" />
        </el-form-item>
        <el-form-item>
          <!-- <el-button @click="doSearch">搜索</el-button> -->
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区 -->
    <div class="mb-2 flex items-center gap-2 toolbar-wrap">
      <el-button type="primary" @click="goToLocationEdit">新增库位</el-button>
      <el-button @click="downloadTemplate">下载导入模板</el-button>
      <el-button @click="openImportDialog">上传导入</el-button>
      <el-button @click="exportData">导出</el-button>
      <el-button type="danger" :disabled="!multipleSelection.length" @click="deleteBatch">批量删除</el-button>
      <el-button :disabled="!multipleSelection.length" @click="openBatchStatusDialog">批量状态变更</el-button>
      <el-button :disabled="!multipleSelection.length" @click="openPrintDialog">批量打印条码/二维码</el-button>
      <el-dropdown>
        <el-button>更多维护<i class="el-icon-arrow-down el-icon--right"></i></el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="goToWarehouseManage">仓库维护</el-dropdown-item>
            <el-dropdown-item @click="goToZoneManage">分区维护</el-dropdown-item>
            <el-dropdown-item @click="goToShelfManage">货架维护</el-dropdown-item>
            <el-dropdown-item @click="goToTypeManage">类型维护</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>

    <!-- 主表格区 -->
    <el-card>
      <el-table
        :data="filteredLocations"
        border
        style="width: 100%"
        @selection-change="onSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="code" label="库位编号" width="120" />
        <el-table-column prop="warehouseName" label="所属仓库" width="120" />
        <el-table-column prop="zoneName" label="分区" width="100" />
        <el-table-column prop="shelfName" label="货架" width="100" />
        <el-table-column prop="level" label="层级" width="80" />
        <el-table-column prop="positionCode" label="位置编号" width="120" />
        <el-table-column prop="type" label="类型" width="100" />
        <el-table-column prop="maxWeight" label="最大重量(kg)" width="120" />
        <el-table-column prop="maxVolume" label="最大体积(m³)" width="120" />
        <el-table-column prop="stock" label="当前库存" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="statusTagType(scope.row.status)">{{ statusText(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="barcode" label="条码" width="120" />
        <el-table-column prop="qrcode" label="二维码" width="100">
          <template #default="scope">
            <img v-if="scope.row.qrcode" :src="scope.row.qrcode" style="width:48px;height:48px;" />
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="120" />
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="scope">
            <div style="display: flex; gap: 8px; justify-content: flex-start; padding: 0 16px; font-size: 13px;">
              <el-button size="small" @click="viewDetail(scope.row)">详情</el-button>
              <el-button size="small" @click="openEditDialog(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="deleteLocation(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="mt-3 flex justify-center"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="filteredLocations.length"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        v-model:current-page="page"
      />
    </el-card>

    <!-- 新增/编辑库位弹窗 -->
    <el-dialog v-model="editDialog.visible" :title="editDialog.data ? '编辑库位' : '新增库位'" width="500px">
      <el-form :model="editDialog.form" label-width="90px">
        <el-form-item label="库位编号" required>
          <el-input v-model="editDialog.form.code" maxlength="20" />
        </el-form-item>
        <el-form-item label="所属仓库" required>
          <div style="display:flex;align-items:center;gap:8px;">
            <el-select v-model="editDialog.form.warehouse" placeholder="请选择仓库" style="width:180px;">
              <el-option v-for="w in warehouseList" :key="w.id" :label="w.name" :value="w.id" />
            </el-select>
            <el-button size="small" @click="openWarehouseDialog()">维护</el-button>
          </div>
        </el-form-item>
        <el-form-item label="分区">
          <div style="display:flex;align-items:center;gap:8px;">
            <el-select v-model="editDialog.form.zone" placeholder="请选择分区" style="width:180px;">
              <el-option v-for="z in filteredZoneOptions" :key="z.id" :label="z.name" :value="z.id" />
            </el-select>
            <el-button size="small" @click="openZoneDialog()">维护</el-button>
          </div>
        </el-form-item>
        <el-form-item label="货架">
          <div style="display:flex;align-items:center;gap:8px;">
            <el-select v-model="editDialog.form.shelf" placeholder="请选择货架" style="width:180px;">
              <el-option v-for="s in filteredShelfOptions" :key="s.id" :label="s.name" :value="s.id" />
            </el-select>
            <el-button size="small" @click="openShelfDialog()">维护</el-button>
          </div>
        </el-form-item>
        <el-form-item label="层级">
          <el-input v-model="editDialog.form.level" maxlength="10" />
        </el-form-item>
        <el-form-item label="位置编号">
          <el-input v-model="editDialog.form.positionCode" maxlength="20" />
        </el-form-item>
        <el-form-item label="类型">
          <div style="display:flex;align-items:center;gap:8px;">
            <el-select v-model="editDialog.form.type" placeholder="请选择类型" style="width:180px;">
              <el-option v-for="t in typeList" :key="t.id" :label="t.name" :value="t.name" />
            </el-select>
            <el-button size="small" @click="openTypeDialog()">类型维护</el-button>
          </div>
        </el-form-item>
        <el-form-item label="最大重量(kg)">
          <el-input-number v-model="editDialog.form.maxWeight" :min="0" />
        </el-form-item>
        <el-form-item label="最大体积(m³)">
          <el-input-number v-model="editDialog.form.maxVolume" :min="0" :step="0.01" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="editDialog.form.status" placeholder="请选择状态">
            <el-option label="可用" value="available" />
            <el-option label="占用" value="occupied" />
            <el-option label="锁定" value="locked" />
            <el-option label="禁用" value="disabled" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="editDialog.form.remark" type="textarea" maxlength="100" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="saveLocation">保存</el-button>
      </template>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog v-model="detailDialog.visible" title="库位详情" width="500px">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="库位编号">{{ detailDialog.data?.code }}</el-descriptions-item>
        <el-descriptions-item label="所属仓库">{{ detailDialog.data?.warehouseName }}</el-descriptions-item>
        <el-descriptions-item label="分区">{{ detailDialog.data?.zoneName }}</el-descriptions-item>
        <el-descriptions-item label="货架">{{ detailDialog.data?.shelfName }}</el-descriptions-item>
        <el-descriptions-item label="层级">{{ detailDialog.data?.level }}</el-descriptions-item>
        <el-descriptions-item label="位置编号">{{ detailDialog.data?.positionCode }}</el-descriptions-item>
        <el-descriptions-item label="类型">{{ typeText(detailDialog.data?.type) }}</el-descriptions-item>
        <el-descriptions-item label="最大重量(kg)">{{ detailDialog.data?.maxWeight }}</el-descriptions-item>
        <el-descriptions-item label="最大体积(m³)">{{ detailDialog.data?.maxVolume }}</el-descriptions-item>
        <el-descriptions-item label="当前库存">{{ detailDialog.data?.stock }}</el-descriptions-item>
        <el-descriptions-item label="状态">{{ statusText(detailDialog.data?.status) }}</el-descriptions-item>
        <el-descriptions-item label="条码">{{ detailDialog.data?.barcode }}</el-descriptions-item>
        <el-descriptions-item label="二维码">
          <img v-if="detailDialog.data?.qrcode" :src="detailDialog.data.qrcode" style="width:80px;height:80px;" />
        </el-descriptions-item>
        <el-descriptions-item label="备注">{{ detailDialog.data?.remark }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialog.visible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 批量打印弹窗 -->
    <el-dialog v-model="printDialog" title="批量打印库位条码/二维码" width="600px">
      <div style="display:flex;flex-wrap:wrap;gap:16px;">
        <div v-for="row in multipleSelection" :key="row.id" style="border:1px solid #eee;padding:8px 12px;width:160px;text-align:center;">
          <div style="font-size:14px;font-weight:bold;">{{ row.code }}</div>
          <div style="font-size:12px;">条码：{{ row.barcode }}</div>
          <img v-if="row.qrcode" :src="row.qrcode" style="width:80px;height:80px;margin:8px 0;" />
        </div>
      </div>
      <template #footer>
        <el-button @click="printDialog=false">取消</el-button>
        <el-button type="primary" @click="doPrint">打印</el-button>
      </template>
    </el-dialog>

    <!-- 批量状态变更弹窗 -->
    <el-dialog v-model="batchStatusDialog" title="批量变更状态" width="400px">
      <el-form>
        <el-form-item label="新状态">
          <el-radio-group v-model="batchStatus">
            <el-radio value="available">可用</el-radio>
            <el-radio value="occupied">占用</el-radio>
            <el-radio value="locked">锁定</el-radio>
            <el-radio value="disabled">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="batchStatusDialog = false">取消</el-button>
        <el-button type="primary" @click="doBatchChangeStatus">确定</el-button>
      </template>
    </el-dialog>

    <!-- 导入弹窗 -->
    <el-dialog v-model="importDialog" title="批量导入库位" width="400px">
      <el-upload
        drag
        :auto-upload="false"
        :show-file-list="true"
        :on-change="file => handleImportFileChange(file.raw)"
        accept=".xlsx,.xls"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将Excel文件拖到此处，或点击上传</div>
      </el-upload>
      <template #footer>
        <el-button @click="importDialog=false">取消</el-button>
        <el-button type="primary" @click="doImport">导入</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="failDetailDialog" title="导入失败明细" width="800px">
      <el-table :data="importResult.failRows" border size="small" style="margin-bottom:12px;">
        <el-table-column prop="code" label="库位编号" />
        <el-table-column prop="warehouseName" label="所属仓库" />
        <el-table-column prop="zoneName" label="分区" />
        <el-table-column prop="shelfName" label="货架" />
        <el-table-column prop="level" label="层级" />
        <el-table-column prop="positionCode" label="位置编号" />
        <el-table-column prop="type" label="类型" />
        <el-table-column prop="maxWeight" label="最大重量" />
        <el-table-column prop="maxVolume" label="最大体积" />
        <el-table-column prop="status" label="状态" />
        <el-table-column prop="remark" label="备注" />
        <el-table-column prop="_reason" label="失败原因" />
      </el-table>
      <template #footer>
        <el-button @click="failDetailDialog=false">关闭</el-button>
        <el-button type="primary" @click="downloadFailDetail">下载失败明细</el-button>
      </template>
    </el-dialog>

    <!-- 仓库类型维护弹窗 -->
    <el-dialog v-model="typeDialog" :title="isTypeEdit ? '编辑类型' : '新增类型'" width="400px">
      <el-form :model="typeEdit" label-width="70px">
        <el-form-item label="类型名称" required>
          <el-input v-model="typeEdit.name" maxlength="10" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="typeEdit.desc" maxlength="30" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="typeEdit.sort" :min="1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="typeDialog=false">取消</el-button>
        <el-button type="primary" @click="saveType">保存</el-button>
      </template>
      <el-table :data="typeList" border size="small" style="margin-top:16px;">
        <el-table-column prop="name" label="类型名称" />
        <el-table-column prop="desc" label="描述" />
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button size="small" @click="openTypeDialog(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteType(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 仓库维护弹窗 -->
    <el-dialog v-model="warehouseDialog" :title="isWarehouseEdit ? '编辑仓库' : '新增仓库'" width="400px">
      <el-form :model="warehouseEdit" label-width="70px">
        <el-form-item label="仓库名称" required>
          <el-input v-model="warehouseEdit.name" maxlength="10" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="warehouseEdit.desc" maxlength="30" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="warehouseEdit.sort" :min="1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="warehouseDialog=false">取消</el-button>
        <el-button type="primary" @click="saveWarehouse">保存</el-button>
      </template>
      <el-table :data="warehouseList" border size="small" style="margin-top:16px;">
        <el-table-column prop="name" label="仓库名称" />
        <el-table-column prop="desc" label="描述" />
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button size="small" @click="openWarehouseDialog(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteWarehouse(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 分区维护弹窗 -->
    <el-dialog v-model="zoneDialog" :title="isZoneEdit ? '编辑分区' : '新增分区'" width="400px">
      <el-form :model="zoneEdit" label-width="70px">
        <el-form-item label="所属仓库" required>
          <el-select v-model="zoneDialogWarehouseId" style="width: 180px">
            <el-option v-for="w in warehouseList" :key="w.id" :label="w.name" :value="w.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="分区名称" required>
          <el-input v-model="zoneEdit.name" maxlength="10" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="zoneEdit.desc" maxlength="30" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="zoneEdit.sort" :min="1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="zoneDialog=false">取消</el-button>
        <el-button type="primary" @click="saveZone">保存</el-button>
      </template>
      <el-table :data="filteredZoneList" border size="small" style="margin-top:16px;">
        <el-table-column label="分区名称">
          <template #default="scope">
            <span>{{ getWarehouseName(scope.row.warehouseId) }} - {{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="desc" label="描述" />
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button size="small" @click="openZoneDialog(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteZone(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 货架维护弹窗 -->
    <el-dialog v-model="shelfDialog" :title="isShelfEdit ? '编辑货架' : '新增货架'" width="400px">
      <el-form :model="shelfEdit" label-width="70px">
        <el-form-item label="所属分区" required>
          <el-select v-model="shelfDialogZoneId" style="width: 180px">
            <el-option v-for="z in zoneList" :key="z.id" :label="z.name" :value="z.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="货架名称" required>
          <el-input v-model="shelfEdit.name" maxlength="10" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="shelfEdit.desc" maxlength="30" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="shelfEdit.sort" :min="1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="shelfDialog=false">取消</el-button>
        <el-button type="primary" @click="saveShelf">保存</el-button>
      </template>
      <el-table :data="filteredShelfList" border size="small" style="margin-top:16px;">
        <el-table-column label="货架名称">
          <template #default="scope">
            <span>{{ getWarehouseName(getZoneWarehouseId(scope.row.zoneId)) }} - {{ getZoneName(scope.row.zoneId) }} - {{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="desc" label="描述" />
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button size="small" @click="openShelfDialog(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteShelf(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import QRCode from 'qrcode'
import * as XLSX from 'xlsx'
import { useRouter } from 'vue-router'
const router = useRouter()

// 仓库维护mock数据
const warehouseList = ref([
  { id: 1, name: '上海仓', desc: '华东主仓', sort: 1 },
  { id: 2, name: '北京仓', desc: '华北主仓', sort: 2 }
])
const warehouseDialog = ref(false)
const warehouseEdit = ref<{id:number,name:string,desc:string,sort:number}>({id:0,name:'',desc:'',sort:1})
const isWarehouseEdit = ref(false)
function openWarehouseDialog(edit?: any) {
  if(edit) {
    warehouseEdit.value = {...edit}
    isWarehouseEdit.value = true
  } else {
    warehouseEdit.value = {id:0,name:'',desc:'',sort:1}
    isWarehouseEdit.value = false
  }
  warehouseDialog.value = true
}
function saveWarehouse() {
  if(!warehouseEdit.value.name) return ElMessage.warning('请输入仓库名称')
  // 只检测名称本身，名称重复即提示
  const isDuplicate = warehouseList.value.some(w => 
    w.name === warehouseEdit.value.name && 
    (isWarehouseEdit.value ? w.id !== warehouseEdit.value.id : true)
  )
  if(isDuplicate) return ElMessage.error('仓库名称已存在，不允许重名！')
  if(isWarehouseEdit.value) {
    const idx = warehouseList.value.findIndex(t=>t.id===warehouseEdit.value.id)
    if(idx>-1) warehouseList.value[idx] = {...warehouseEdit.value}
    ElMessage.success('仓库修改成功')
  } else {
    warehouseList.value.push({
      id: Date.now(),
      name: warehouseEdit.value.name,
      desc: warehouseEdit.value.desc,
      sort: warehouseEdit.value.sort
    })
    ElMessage.success('仓库新增成功')
  }
  warehouseDialog.value = false
}
function canDeleteWarehouse(warehouseId: number) {
  return !locationList.value.some(l => l.warehouse === warehouseId && l.stock > 0)
}
function deleteWarehouse(row: { id: number }) {
  if (!canDeleteWarehouse(row.id)) {
    ElMessage.error('该仓库下存在商品库存，无法删除！')
    return
  }
  ElMessageBox.confirm('确定要删除该仓库吗？','提示',{type:'warning'}).then(()=>{
    warehouseList.value = warehouseList.value.filter(t=>t.id!==row.id)
    ElMessage.success('删除成功')
  })
}
// 分区维护mock数据，增加warehouseId字段
const zoneList = ref([
  { id: 1, warehouseId: 1, name: 'A区', desc: '主分区', sort: 1 },
  { id: 2, warehouseId: 1, name: 'B区', desc: '次分区', sort: 2 },
  { id: 3, warehouseId: 2, name: 'C区', desc: '北京分区', sort: 1 }
])
const zoneDialog = ref(false)
// 分区编辑对象增加warehouseId
const zoneEdit = ref<{id:number,warehouseId:number,name:string,desc:string,sort:number}>({id:0,warehouseId:0,name:'',desc:'',sort:1})
const isZoneEdit = ref(false)
// 分区维护弹窗增加仓库选择
const zoneDialogWarehouseId = ref<number>(warehouseList.value[0]?.id || 0)
const filteredZoneList = computed(() => zoneList.value.filter(z => z.warehouseId === zoneDialogWarehouseId.value))
function openZoneDialog(edit?: any) {
  if(edit) {
    zoneEdit.value = { ...edit }
    isZoneEdit.value = true
  } else {
    zoneEdit.value = { id: 0, warehouseId: zoneDialogWarehouseId.value, name: '', desc: '', sort: 1 }
    isZoneEdit.value = false
  }
  zoneDialog.value = true
}
function saveZone() {
  if(!zoneEdit.value.name) return ElMessage.warning('请输入分区名称')
  if(!zoneEdit.value.warehouseId) return ElMessage.warning('请选择所属仓库')
  // 校验同一仓库下分区名称不能重复
  const isDuplicate = zoneList.value.some(z => 
    z.name === zoneEdit.value.name && z.warehouseId === zoneEdit.value.warehouseId && (isZoneEdit.value ? z.id !== zoneEdit.value.id : true)
  )
  if(isDuplicate) return ElMessage.error('同一仓库下分区名称已存在，不允许重名！')
  if(isZoneEdit.value) {
    const idx = zoneList.value.findIndex(t=>t.id===zoneEdit.value.id)
    if(idx>-1) zoneList.value[idx] = {...zoneEdit.value}
    ElMessage.success('分区修改成功')
  } else {
    zoneList.value.push({
      id: Date.now(),
      warehouseId: zoneEdit.value.warehouseId,
      name: zoneEdit.value.name,
      desc: zoneEdit.value.desc,
      sort: zoneEdit.value.sort
    })
    ElMessage.success('分区新增成功')
  }
  zoneDialog.value = false
}
function canDeleteZone(zoneId: number, warehouseId?: number) {
  // 只校验本仓库下本分区的库位
  return !locationList.value.some(l => l.zone === zoneId && l.warehouse === warehouseId && l.stock > 0)
}
function deleteZone(row: { id: number, warehouseId?: number }) {
  if (!canDeleteZone(row.id, row.warehouseId)) {
    ElMessage.error('该分区下存在商品库存，无法删除！')
    return
  }
  ElMessageBox.confirm('确定要删除该分区吗？','提示',{type:'warning'}).then(()=>{
    zoneList.value = zoneList.value.filter(t=>t.id!==row.id)
    ElMessage.success('删除成功')
  })
}
// 货架维护mock数据，增加zoneId字段
const shelfList = ref([
  { id: 1, zoneId: 1, name: 'A1货架', desc: 'A区主货架', sort: 1 },
  { id: 2, zoneId: 1, name: 'A2货架', desc: 'A区副货架', sort: 2 },
  { id: 3, zoneId: 2, name: 'B1货架', desc: 'B区主货架', sort: 1 },
  { id: 4, zoneId: 3, name: 'C1货架', desc: 'C区主货架', sort: 1 }
])
const shelfDialog = ref(false)
// 货架编辑对象增加zoneId
const shelfEdit = ref<{id:number,zoneId:number,name:string,desc:string,sort:number}>({id:0,zoneId:0,name:'',desc:'',sort:1})
const isShelfEdit = ref(false)
// 货架维护弹窗增加分区选择
const shelfDialogZoneId = ref<number>(zoneList.value[0]?.id || 0)
const filteredShelfList = computed(() => shelfList.value.filter(s => s.zoneId === shelfDialogZoneId.value))
function openShelfDialog(edit?: any) {
  if(edit) {
    shelfEdit.value = { ...edit }
    isShelfEdit.value = true
  } else {
    shelfEdit.value = { id: 0, zoneId: shelfDialogZoneId.value, name: '', desc: '', sort: 1 }
    isShelfEdit.value = false
  }
  shelfDialog.value = true
}
function saveShelf() {
  if(!shelfEdit.value.name) return ElMessage.warning('请输入货架名称')
  if(!shelfEdit.value.zoneId) return ElMessage.warning('请选择所属分区')
  // 找到当前分区的所属仓库id
  const currentZone = zoneList.value.find(z => z.id === shelfEdit.value.zoneId)
  const warehouseId = currentZone?.warehouseId
  // 校验同一仓库+分区下货架名称不能重复
  const isDuplicate = shelfList.value.some(s => {
    if (s.id === shelfEdit.value.id && isShelfEdit.value) return false
    const sZone = zoneList.value.find(z => z.id === s.zoneId)
    return s.name === shelfEdit.value.name && s.zoneId === shelfEdit.value.zoneId && sZone?.warehouseId === warehouseId
  })
  if(isDuplicate) return ElMessage.error('同一仓库下同一分区的货架名称已存在，不允许重名！')
  if(isShelfEdit.value) {
    const idx = shelfList.value.findIndex(t=>t.id===shelfEdit.value.id)
    if(idx>-1) shelfList.value[idx] = {...shelfEdit.value}
    ElMessage.success('货架修改成功')
  } else {
    shelfList.value.push({
      id: Date.now(),
      zoneId: shelfEdit.value.zoneId,
      name: shelfEdit.value.name,
      desc: shelfEdit.value.desc,
      sort: shelfEdit.value.sort
    })
    ElMessage.success('货架新增成功')
  }
  shelfDialog.value = false
}
function canDeleteShelf(shelfId: number, zoneId?: number) {
  // 只校验本分区下本货架的库位
  return !locationList.value.some(l => l.shelf === shelfId && l.zone === zoneId && l.stock > 0)
}
function deleteShelf(row: { id: number, zoneId?: number }) {
  if (!canDeleteShelf(row.id, row.zoneId)) {
    ElMessage.error('该货架下存在商品库存，无法删除！')
    return
  }
  ElMessageBox.confirm('确定要删除该货架吗？','提示',{type:'warning'}).then(()=>{
    shelfList.value = shelfList.value.filter(t=>t.id!==row.id)
    ElMessage.success('删除成功')
  })
}

// mock 库位数据（初始化时自动生成条码和二维码）
function genBarcodeAndQrcode(row: any) {
  const barcode = `${row.warehouseName}-${row.zoneName}-${row.shelfName}-${row.level}-${row.positionCode}`
  row.barcode = barcode
  return QRCode.toDataURL(barcode).then((url: string) => {
    row.qrcode = url
    return row
  })
}
// mock数据中的type字段也用中文
const rawMock = [
  { id: 1, code: 'A1-01', warehouse: 1, warehouseName: '上海仓', zone: 1, zoneName: 'A区', shelf: 1, shelfName: 'A1货架', level: '1', positionCode: 'P001', type: '普通', maxWeight: 1000, maxVolume: 10, stock: 60, status: 'available', remark: '主通道' },
  { id: 2, code: 'A1-02', warehouse: 1, warehouseName: '上海仓', zone: 1, zoneName: 'A区', shelf: 1, shelfName: 'A1货架', level: '2', positionCode: 'P002', type: '普通', maxWeight: 1000, maxVolume: 10, stock: 80, status: 'occupied', remark: '' },
  { id: 3, code: 'B1-01', warehouse: 2, warehouseName: '北京仓', zone: 2, zoneName: 'B区', shelf: 3, shelfName: 'B1货架', level: '1', positionCode: 'P003', type: '普通', maxWeight: 800, maxVolume: 8, stock: 30, status: 'available', remark: '' },
]
const locationList = ref<any[]>([])
Promise.all(rawMock.map(row => genBarcodeAndQrcode({ ...row }))).then(list => { locationList.value = list })

// 仓库类型维护mock数据
const typeList = ref([
  { id: 1, name: '普通', desc: '常规库位', sort: 1 },
  { id: 2, name: '冷藏', desc: '低温冷藏', sort: 2 },
  { id: 3, name: '危险品', desc: '特殊危险品', sort: 3 }
])
// 类型维护弹窗
const typeDialog = ref(false)
const typeEdit = ref<{id:number,name:string,desc:string,sort:number}>({id:0,name:'',desc:'',sort:1})
const isTypeEdit = ref(false)
function openTypeDialog(edit?: any) {
  if(edit) {
    typeEdit.value = {...edit}
    isTypeEdit.value = true
  } else {
    typeEdit.value = {id:0,name:'',desc:'',sort:1}
    isTypeEdit.value = false
  }
  typeDialog.value = true
}
function saveType() {
  if(!typeEdit.value.name) return ElMessage.warning('请输入类型名称')
  if(isTypeEdit.value) {
    const idx = typeList.value.findIndex(t=>t.id===typeEdit.value.id)
    if(idx>-1) typeList.value[idx] = {...typeEdit.value}
    ElMessage.success('类型修改成功')
  } else {
    typeList.value.push({
      id: Date.now(),
      name: typeEdit.value.name,
      desc: typeEdit.value.desc,
      sort: typeEdit.value.sort
    })
    ElMessage.success('类型新增成功')
  }
  typeDialog.value = false
}
function deleteType(row: { id: number; name: string; desc: string; sort: number }) {
  ElMessageBox.confirm('确定要删除该类型吗？','提示',{type:'warning'}).then(()=>{
    typeList.value = typeList.value.filter(t=>t.id!==row.id)
    ElMessage.success('删除成功')
  })
}

const filter = ref({
  warehouse: '',
  zone: '',
  shelf: '',
  status: '',
  keyword: ''
})
const page = ref(1)
const pageSize = ref(20)
const multipleSelection = ref<any[]>([])

const filteredLocations = computed(() => {
  let list = locationList.value
  if (filter.value.warehouse) list = list.filter(l => l.warehouse === filter.value.warehouse)
  if (filter.value.zone) list = list.filter(l => l.zone === filter.value.zone)
  if (filter.value.shelf) list = list.filter(l => l.shelf === filter.value.shelf)
  if (filter.value.status) list = list.filter(l => l.status === filter.value.status)
  if (filter.value.keyword) {
    const k = filter.value.keyword.trim()
    list = list.filter(l => l.code.includes(k) || l.barcode.includes(k) || (l.remark && l.remark.includes(k)))
  }
  // 分页（简单模拟）
  const start = (page.value - 1) * 20
  return list.slice(start, start + 20)
})

function doSearch() {
  page.value = 1
}
function resetFilter() {
  filter.value = { warehouse: '', zone: '', shelf: '', status: '', keyword: '' }
  page.value = 1
}
function onSelectionChange(val: any[]) {
  multipleSelection.value = val
}

// 编辑弹窗
const editDialog = ref({ visible: false, data: null as any, form: { code: '', warehouse: 0, zone: 0, shelf: 0, level: '', positionCode: '', type: '', maxWeight: 0, maxVolume: 0, status: 'available', barcode: '', qrcode: '', remark: '' } })
function openEditDialog(row: any) {
  // 跳转到库位编辑页面，带上id参数
  router.push({ path: '/warehouse/location-edit', query: { id: row.id } })
}
// 保存时根据表单内容重新生成条码和二维码
function saveLocation() {
  const f = editDialog.value.form
  if (!f.code) return ElMessage.warning('请填写库位编号')
  if (!f.warehouse) return ElMessage.warning('请选择所属仓库')
  // 生成条码内容
  const warehouseName = getWarehouseName(f.warehouse)
  const zoneName = getZoneName(f.zone)
  const shelfName = getShelfName(f.shelf)
  const barcode = `${warehouseName}-${zoneName}-${shelfName}-${f.level}-${f.positionCode}`
  f.barcode = barcode
  return QRCode.toDataURL(barcode).then((url: string) => {
    f.qrcode = url
    if (editDialog.value.data) {
      // 编辑
      const idx = locationList.value.findIndex(l => l.id === editDialog.value.data.id)
      if (idx > -1) locationList.value[idx] = { ...f, id: editDialog.value.data.id, warehouseName, zoneName, shelfName }
      ElMessage.success('编辑成功')
    } else {
      // 新增
      const newId = Date.now()
      locationList.value.unshift({ ...f, id: newId, warehouseName, zoneName, shelfName, stock: 0 })
      ElMessage.success('新增成功')
    }
    editDialog.value.visible = false
  })
}
function deleteLocation(row: { id: number }) {
  if (!canDeleteLocation(row.id)) {
    ElMessage.error('该库位存在商品库存，无法删除！')
    return
  }
  ElMessageBox.confirm('确定要删除该库位吗？', '提示', { type: 'warning' })
    .then(() => {
      locationList.value = locationList.value.filter(l => l.id !== row.id)
      ElMessage.success('删除成功')
    })
    .catch(() => {})
}
function deleteBatch() {
  if (!multipleSelection.value.length) return
  // 校验选中库位是否有库存
  if (multipleSelection.value.some(l => l.stock > 0)) {
    ElMessage.error('选中的库位中存在商品库存，无法批量删除！')
    return
  }
  ElMessageBox.confirm('确定要批量删除选中的库位吗？', '提示', { type: 'warning' })
    .then(() => {
      const ids = multipleSelection.value.map(l => l.id)
      locationList.value = locationList.value.filter(l => !ids.includes(l.id))
      ElMessage.success('批量删除成功')
      multipleSelection.value = []
    })
    .catch(() => {})
}
function exportData() {
  // 优先导出选中内容，无选中则导出全部
  const exportRows = multipleSelection.value.length > 0 ? multipleSelection.value : filteredLocations.value
  const header = [
    '库位编号','所属仓库','分区','货架','层级','位置编号','类型','最大重量(kg)','最大体积(m³)','当前库存','状态','条码','备注'
  ]
  const rows = exportRows.map(row => [
    row.code,
    row.warehouseName,
    row.zoneName,
    row.shelfName,
    row.level,
    row.positionCode,
    row.type,
    row.maxWeight,
    row.maxVolume,
    row.stock,
    statusText(row.status),
    row.barcode,
    row.remark
  ])
  const ws = XLSX.utils.aoa_to_sheet([header, ...rows])
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, '库位列表')
  XLSX.writeFile(wb, '库位列表.xlsx')
}
// 批量状态变更功能实现
const batchStatusDialog = ref(false)
const batchStatus = ref('available')
function openBatchStatusDialog() {
  if (!multipleSelection.value.length) return ElMessage.warning('请先选择要变更的库位')
  batchStatus.value = 'available'
  batchStatusDialog.value = true
}
function doBatchChangeStatus() {
  multipleSelection.value.forEach(item => {
    const loc = locationList.value.find(l => l.id === item.id)
    if (loc) loc.status = batchStatus.value
  })
  batchStatusDialog.value = false
  ElMessage.success('批量状态变更成功')
}

// 详情弹窗
const detailDialog = ref({ visible: false, data: null as any })
function viewDetail(row: any) {
  detailDialog.value.data = row
  detailDialog.value.visible = true
}

function statusText(status: string) {
  switch (status) {
    case 'available': return '可用'
    case 'occupied': return '占用'
    case 'locked': return '锁定'
    case 'disabled': return '禁用'
    default: return status
  }
}
function statusTagType(status: string) {
  switch (status) {
    case 'available': return 'success'
    case 'occupied': return 'warning'
    case 'locked': return 'info'
    case 'disabled': return 'danger'
    default: return ''
  }
}
function typeText(type: string) {
  return type || ''
}
function getWarehouseName(id: number) {
  const w = warehouseList.value.find(w => w.id === id)
  return w ? w.name : ''
}
function getZoneName(id: number) {
  const z = zoneList.value.find(z => z.id === id)
  return z ? z.name : ''
}
function getShelfName(id: number) {
  const s = shelfList.value.find(s => s.id === id)
  return s ? s.name : ''
}
function canDeleteLocation(locationId: number) {
  const loc = locationList.value.find(l => l.id === locationId)
  return !loc || loc.stock === 0
}

// 批量打印弹窗
const printDialog = ref(false)
function openPrintDialog() {
  if (!multipleSelection.value.length) return ElMessage.warning('请先选择要打印的库位')
  printDialog.value = true
}
function doPrint() {
  window.print()
}

// 导入弹窗
const importDialog = ref(false)
const importFile = ref<File|null>(null)
function openImportDialog() {
  importDialog.value = true
  importFile.value = null
}
function handleImportFileChange(file: File) {
  importFile.value = file
}
// 字段自动匹配映射
const FIELD_MAP: Record<string, string> = {
  '库位编号': 'code', '编号': 'code', '库位号': 'code',
  '所属仓库': 'warehouseName', '仓库': 'warehouseName',
  '分区': 'zoneName',
  '货架': 'shelfName',
  '层级': 'level',
  '位置编号': 'positionCode', '位置': 'positionCode',
  '类型': 'type',
  '最大重量': 'maxWeight', '最大重量(kg)': 'maxWeight',
  '最大体积': 'maxVolume', '最大体积(m³)': 'maxVolume',
  '状态': 'status',
  '备注': 'remark'
}
const TYPE_ENUM = ['普通','冷藏','危险品']
const STATUS_ENUM = ['available','occupied','locked','disabled','可用','占用','锁定','禁用']

const importResult = ref<{success:number,fail:number,failRows:any[]}>({success:0,fail:0,failRows:[]})

async function doImport() {
  if (!importFile.value) return ElMessage.warning('请先选择文件')
  const data = await importFile.value.arrayBuffer()
  const workbook = XLSX.read(data, { type: 'array' })
  const sheet = workbook.Sheets[workbook.SheetNames[0]]
  const rows = XLSX.utils.sheet_to_json(sheet, {header:1})
  if (!rows.length) return ElMessage.warning('导入数据为空')
  const header = rows[0] as string[]
  const body = rows.slice(1)
  // 字段自动匹配
  const fieldKeys = header.map(h=>FIELD_MAP[h.trim()]||'')
  // 校验与导入
  let success = 0, fail = 0, failRows:any[] = [], newRows:any[] = []
  for(const row of body) {
    const obj:any = {}
    fieldKeys.forEach((k,i)=>{ if(k) obj[k]=row[i] })
    // 校验
    let reason = ''
    if(!obj.code) reason+='库位编号不能为空;'
    if(!obj.warehouseName) reason+='所属仓库不能为空;'
    if(!obj.shelfName) reason+='货架不能为空;'
    if(!obj.level) reason+='层级不能为空;'
    if(!obj.positionCode) reason+='位置编号不能为空;'
    if(obj.maxWeight!==undefined && isNaN(Number(obj.maxWeight))) reason+='最大重量需为数字;'
    if(obj.maxVolume!==undefined && isNaN(Number(obj.maxVolume))) reason+='最大体积需为数字;'
    if(obj.type && !TYPE_ENUM.includes(obj.type)) reason+='类型不合法;'
    if(obj.status && !STATUS_ENUM.includes(obj.status)) reason+='状态不合法;'
    // 组合唯一性校验
    if(newRows.some(r=>r.code===obj.code&&r.warehouseName===obj.warehouseName&&r.shelfName===obj.shelfName&&r.level===obj.level&&r.positionCode===obj.positionCode)) reason+='同一批导入中库位唯一性冲突;'
    if(reason) {
      fail++
      failRows.push({...obj,_reason:reason})
      continue
    }
    // 生成条码和二维码
    const barcode = `${obj.warehouseName}-${obj.zoneName||''}-${obj.shelfName}-${obj.level}-${obj.positionCode}`
    const qrcode = await QRCode.toDataURL(barcode)
    newRows.push({
      id: Date.now() + Math.floor(Math.random()*10000),
      code: obj.code,
      warehouse: 0,
      warehouseName: obj.warehouseName,
      zone: 0,
      zoneName: obj.zoneName||'',
      shelf: 0,
      shelfName: obj.shelfName,
      level: obj.level,
      positionCode: obj.positionCode,
      type: obj.type||'',
      maxWeight: Number(obj.maxWeight)||0,
      maxVolume: Number(obj.maxVolume)||0,
      stock: 0,
      status: obj.status||'available',
      barcode,
      qrcode,
      remark: obj.remark||''
    })
    success++
  }
  locationList.value.unshift(...newRows)
  importResult.value = {success,fail,failRows}
  ElMessage.success(`导入完成，成功${success}条，失败${fail}条`)
  importDialog.value = false
  if(fail>0) failDetailDialog.value = true
}
function downloadTemplate() {
  const header = [
    ['库位编号','所属仓库','分区','货架','层级','位置编号','类型','最大重量','最大体积','状态','备注']
  ]
  const ws = XLSX.utils.aoa_to_sheet(header)
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, '模板')
  XLSX.writeFile(wb, '库位导入模板.xlsx')
}
// 失败明细弹窗
const failDetailDialog = ref(false)
function downloadFailDetail() {
  if(!importResult.value.failRows.length) return
  const header = ['库位编号','所属仓库','分区','货架','层级','位置编号','类型','最大重量','最大体积','状态','备注','失败原因']
  const data = importResult.value.failRows.map(r=>[
    r.code||'',r.warehouseName||'',r.zoneName||'',r.shelfName||'',r.level||'',r.positionCode||'',r.type||'',r.maxWeight||'',r.maxVolume||'',r.status||'',r.remark||'',r._reason||''
  ])
  const ws = XLSX.utils.aoa_to_sheet([header,...data])
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, '失败明细')
  XLSX.writeFile(wb, '库位导入失败明细.xlsx')
}

// 级联下拉：根据所选仓库、分区动态过滤分区和货架
const filteredZoneOptions = computed(() => zoneList.value.filter(z => z.warehouseId === (editDialog.value.form?.warehouse ?? 0)))
const filteredShelfOptions = computed(() => shelfList.value.filter(s => s.zoneId === (editDialog.value.form?.zone ?? 0)))
// 监听仓库变更，自动重置分区和货架
watch(() => editDialog.value.form?.warehouse, (val) => {
  if (!editDialog.value.form) return
  editDialog.value.form.zone = undefined
  editDialog.value.form.shelf = undefined
})
// 监听分区变更，自动重置货架
watch(() => editDialog.value.form?.zone, (val) => {
  if (!editDialog.value.form) return
  editDialog.value.form.shelf = undefined
})

// 新增辅助方法
function getZoneWarehouseId(zoneId: number) {
  const zone = zoneList.value.find(z => z.id === zoneId)
  return zone?.warehouseId || 0
}

// 新增库位跳转
function goToLocationEdit() {
  router.push('/warehouse/location-edit')
}
// 跳转到各维护页面
function goToWarehouseManage() {
  router.push('/warehouse/warehouse-manage')
}
function goToZoneManage() {
  router.push('/warehouse/zone-manage')
}
function goToShelfManage() {
  router.push('/warehouse/shelf-manage')
}
function goToTypeManage() {
  router.push('/warehouse/type-manage')
}
</script>

<style scoped>
.location-manage-page {
  padding: 24px;
  background: #f7f8fa;
  min-height: 100vh;
}
.mb-3 { margin-bottom: 24px; }
.mb-2 { margin-bottom: 12px; }
.mt-3 { margin-top: 24px; }
.flex { display: flex; }
.items-center { align-items: center; }
.gap-2 { gap: 8px; }
.toolbar-wrap { flex-wrap: wrap; }
</style> 